﻿using System;
using System.Linq;
using System.Web.Mvc;
using KLS.PPDS.ApplicationService.Manager;
using KLS.PPDS.Utilities;
using KLS.PPDS.Utilities.Attributes;
using KLS.PPDS.Utilities.BaseController;
using KLS.PPDS.Utility;
using KLS.PPDS.Web.Models;
using KLS.PPDS.Resources;

namespace KLS.PPDS.Web.Controllers.Publication
{
    ///<summary>
    /// Controller class for the publicaton screen
    ///</summary>
    public class PublicationController : BaseController
    {
        //
        // GET: /Publication/
        ///<summary>
        /// main action for the publication page
        ///</summary>
        ///<param name="model"></param>
        ///<returns></returns>
        [AjaxAuthorize(Roles = RoleConstant.All)]
        public ActionResult Index(PublicationViewModel model)
        {
            ModelState.Clear();
            ViewData.Clear();

            ViewData[CommonConstant.Company] = new SelectList(PublicationModel.GetAllCompanyForModel().OrderBy(c => c.CompanyName).ToList(), "Id", "CompanyName");
            ViewData[CommonConstant.Year] = new SelectList(YearMonthManager.GetYear(CommonSession.CompanyId).OrderBy(c=>c).ToList(), DateTime.Now.Year.ToString());
            ViewData[CommonConstant.Month] = new SelectList(YearMonthManager.GetMonths(), "Month", "Name");

            

            PublicationModel.ProcessIndexModel(model);

            // CommonTask.SendMail("maw@bordingvista.com", "moon.bluewolf@gmail.com","test mail"," just body :D " );

            return View(model);
        }

        /// <summary>
        /// retun publicatoin list grid user controll
        /// </summary>
        /// <param name="model"></param>
        /// <param name="SrchCompanyId"></param>
        /// <param name="SrchYear"></param>
        /// <param name="SrchMonth"></param>
        /// <returns></returns>
        [AjaxAuthorize(Roles = RoleConstant.All)]
        public ActionResult PublicationList(PublicationViewModel model, int? SrchCompanyId, int? SrchYear, int? SrchMonth)
        {
            //ViewData[CommonConstant.Year] = new SelectList(YearMonthManager.GetYear());
            //ViewData[CommonConstant.Month] = new SelectList(YearMonthManager.GetMonths(), "Month", "Name");
            
            if (SrchCompanyId != null)
                model.SrchCompanyId = SrchCompanyId.GetValueOrDefault(0);
            if (SrchYear != null)
                model.SrchYear = SrchYear.GetValueOrDefault(0);
            if (SrchMonth != null)
                model.SrchMonth = SrchMonth.GetValueOrDefault(0);

            PublicationModel.ProcessIndexModel(model);
            return View(model);
        }

        /// <summary>
        /// return the publiation setting user controll in New mode
        /// </summary>
        /// <param name="model"></param>
        /// <param name="SrchCompanyId"></param>
        /// <param name="SrchYear"></param>
        /// <param name="SrchMonth"></param>
        /// <returns></returns>
        [AjaxAuthorize(Roles = RoleConstant.SuperadminOrEditor)]
        public ActionResult Add(PublicationSaveViewModel model, int? SrchCompanyId, int? SrchYear, int? SrchMonth)
        {
            if (CommonSession.IsUserSuperAdmin || CommonSession.IsUserSuperAdminOrGraphic)
            {
                model.CompanyId = SrchCompanyId.GetValueOrDefault(0);
            }
            else
            {
                model.CompanyId = CommonSession.CompanyId;
            }
            
            model.Year = SrchYear.GetValueOrDefault(DateTime.Today.Year);
            model.Month = SrchMonth.GetValueOrDefault(DateTime.Today.Month);

            ViewData.Clear();
            ViewData["companies"] = new SelectList(CompanyManager.GetAllCompany().OrderBy(c => c.CompanyName).ToList(), "Id", "CompanyName");
            ViewData["years"] = new SelectList(YearMonthManager.GetYear(CommonSession.CompanyId).OrderBy(c => c).ToList(), model.Year.ToString());
            ViewData["months"] = new SelectList(YearMonthManager.GetMonths(), "Month", "Name", model.Month.ToString());

            //if (model.CompanyId == 0)
            //{
            //   return JsonMessage("Please select a company");
            //}

            return View(model);
        }

        /// <summary>
        /// returns the publicaton setttings user controll in edit mode
        /// </summary>
        /// <param name="model"></param>
        /// <param name="PublicationId"></param>
        /// <param name="SrchCompanyId"></param>
        /// <param name="SrchYear"></param>
        /// <param name="SrchMonth"></param>
        /// <returns></returns>
        [AjaxAuthorize(Roles = RoleConstant.All)]
        public ActionResult Edit(PublicationSaveViewModel model, int? PublicationId, int? SrchCompanyId, int? SrchYear, int? SrchMonth)
        {
            PublicationModel.ProcessEditModel(model, PublicationId);
            ViewData["companies"] = new SelectList(CompanyManager.GetAllCompany().OrderBy(c => c.CompanyName).ToList(), "Id", "CompanyName");
            ViewData["years"] = new SelectList(YearMonthManager.GetYear(CommonSession.CompanyId).OrderBy(c => c).ToList(), model.Year.ToString());
            ViewData["months"] = new SelectList(YearMonthManager.GetMonths(), "Month", "Name", model.Month.ToString());

            return View("Add", model);
        }

        ///<summary>
        /// Add or update a publication to the database
        ///</summary>
        ///<param name="model"></param>
        ///<param name="SrchCompanyId"></param>
        ///<param name="SrchYear"></param>
        ///<param name="SrchMonth"></param>
        ///<returns></returns>
        [HttpPost]
        [AjaxAuthorize(Roles = RoleConstant.SuperadminOrEditor)]
        public ActionResult Save(PublicationSaveViewModel model, int? SrchCompanyId, int? SrchYear, int? SrchMonth)
        {          
            KLS.PPDS.Core.Entity.Publication publication = new Core.Entity.Publication() ;
         
            


            if (model.Id > 0) 
            {
                publication = PublicationManager.GetPublicationById(model.Id);

                //publication rename checking
                if (model.PublicationName.Equals(publication.PublicationName).Equals(false)) 
                {
                    var arts = ArticleManager.GetArticleByPublicationId(model.Id).Where(c => c.IsReadyForGraphic.Equals(true)).ToList();

                    if (arts != null && arts.Count > 0) 
                    {
                        return JsonMessage(CommonMessage.PublicationCanNotReaname);
                    }


                   
                }
                //publication company change checking
                if (model.CompanyId.Equals(publication.CompanyId).Equals(false)) 
                {
                    var arts = ArticleManager.GetArticleByPublicationId(model.Id).Where(c => c.IsReadyForGraphic.Equals(true)).ToList();

                    if (arts != null && arts.Count > 0)
                    {
                        return JsonMessage(CommonMessage.PublicationCompanyCanNotChange);
                    }
                }
                
            }

            model.CopyPropertyValue<PublicationSaveViewModel, KLS.PPDS.Core.Entity.Publication>(publication);

            PublicationManager.Save(publication);

            //string oldPackpath = ArticleContentModel.GetPackagePublicationBaseFolder(publication.Id);
            //string newPackpath = ArticleContentModel.GetPackagePublicationBaseFolder(publication);

            //if (oldPackpath != newPackpath)
            //{
            //    FileUtil.RemaneDirectory(oldPackpath, newPackpath);
            //}
            //try
            //{
            //    PublicationManager.Save(publication);
            //}
            //catch (Exception ex)
            //{
            //    if (oldPackpath != newPackpath)
            //    {
            //        FileUtil.RemaneDirectory(newPackpath, oldPackpath);
            //    }
            //    throw ex;
            //}
            if (model.OldComapnyId > 0 && model.OldComapnyId.Equals(model.CompanyId).Equals(false)) 
            {
                var oldF = ArticleContentModel.GetPulicationBaseFolder(model.OldComapnyId, model.Id);
                var newF = ArticleContentModel.GetPulicationBaseFolder(model.CompanyId, model.Id);

                FileUtil.MoveFolder(oldF, newF);
            }


            return RedirectToAction("PublicationList", new { @SrchCompanyId = SrchCompanyId, @SrchYear = SrchYear, @SrchMonth = SrchMonth });          
        }

        /// <summary>
        /// Set the delete flag true for the specified publication
        /// </summary>
        /// <param name="PublicationId">PublicationId to be deleted</param>
        /// <param name="SrchCompanyId"> </param>
        /// <param name="SrchYear"></param>
        /// <param name="SrchMonth"></param>
        /// <returns></returns>
        public ActionResult Delete(int? PublicationId, int? SrchCompanyId, int? SrchYear, int? SrchMonth)
         {

             PublicationManager.Delete(PublicationId.GetValueOrDefault(0));
             // ModelState.Clear();
             var random = new Random();
             var x = random.Next(1000);
             return RedirectToAction("PublicationList", new { @SrchCompanyId = SrchCompanyId, @SrchYear = SrchYear, @SrchMonth = SrchMonth, @randomNum = random.Next(1, 100) });
             //ModelState.Clear();

             //var model = new PublicationViewModel();

             //if (SrchCompanyId != null)
             //    model.SrchCompanyId = SrchCompanyId.GetValueOrDefault(0);
             //if (SrchYear != null)
             //    model.SrchYear = SrchYear.GetValueOrDefault(0);
             //if (SrchMonth != null)
             //    model.SrchMonth = SrchMonth.GetValueOrDefault(0);

             //PublicationModel.ProcessIndexModel(model);

             //return View("~/Views/Publication/Index.ascx", model);
         }
    }
}
